﻿using FluentValidation;
using Microsoft.AspNetCore.Mvc.Filters;
using Services.Initial.PublicProject.PublicClass.ExtensionException;
using System.Reflection;
using Zack.Commons;
namespace Services.Initial.Filters;

public class ValidatorFilter(IServiceProvider serviceProvider) : IAsyncActionFilter
{
    private readonly IServiceProvider serviceProvider = serviceProvider;
    async Task IAsyncActionFilter.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        #region 使用反射获取所有的验证器
        // 获取程序集中的所有类型
        //var assemblies = ReflectionHelper.GetAllReferencedAssemblies();
        //foreach (var assembly in assemblies)
        //{
        //    types.AddRange(assembly.GetTypes());
        //}
        //var types = new List<Type>();
        //types.AddRange(Assembly.GetEntryAssembly()!.GetTypes());
        //foreach (var argument in context.ActionArguments)
        //{
        //    var argumentType = argument.Value!.GetType();
        //    var validatorType = typeof(AbstractValidator<>).MakeGenericType(argumentType);
        //    foreach (var type in types)
        //    {
        //        // 如果类型是 validatorType 的子类，并且不是抽象的
        //        if (type.IsSubclassOf(validatorType) && !type.IsAbstract)
        //        {
        //            var validator = Activator.CreateInstance(type) as IValidator;
        //            //创建好验证实例和参数实例，并进行验证 
        //            var validatorContextType = typeof(ValidationContext<>).MakeGenericType(argumentType);
        //            var validatorContext = Activator.CreateInstance(validatorContextType, [argument.Value]) as IValidationContext;
        //            var validationResult = await validator.ValidateAsync(validatorContext);
        //            if (!validationResult.IsValid)
        //            {
        //                string message = "";
        //                foreach (var error in validationResult.Errors)
        //                {
        //                    message += error.ErrorMessage + ";";
        //                }
        //                throw new ExceptionWithStatus(System.Net.HttpStatusCode.BadRequest, message);
        //            }
        //            break;
        //        }
        //    }
        //}
        #endregion

        #region  从serviceProvider中获取当前参数的类型并获取其验证器
        foreach (var argument in context.ActionArguments)
        {
            var argumentType = argument.Value!.GetType();
            var validatorType = typeof(IValidator<>).MakeGenericType(argumentType);
            var validator = serviceProvider.GetService(validatorType) as IValidator;
            if (validator != null)
            {
                var validatorContextType = typeof(ValidationContext<>).MakeGenericType(argumentType);
                var validatorContext = Activator.CreateInstance(validatorContextType, [argument.Value]) as IValidationContext;
                var validationResult = await validator.ValidateAsync(validatorContext);
                if (!validationResult.IsValid)
                {
                    string message = "";
                    foreach (var error in validationResult.Errors)
                    {
                        message += error.ErrorMessage + ";";
                    }
                    throw new ExceptionWithStatus(System.Net.HttpStatusCode.BadRequest, message);
                }
            }
        }
        #endregion
        // 继续执行后续的ActionFilter
        await next();
     }
}
